﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using CommDll;

namespace InstitutionAssitant
{
    /// <summary>
    /// ClassName:frmPlatformOrder
    /// Version:1.0
    /// Date:2019-06-04
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为本地配送处理
    /// </remarks>
    public partial class frmDelivery : DevComponents.DotNetBar.OfficeForm
    {
        #region 01.自定义属性
        int m_nFieldSelectedOrder = 1;  // 选择列所在顺序位置(0为起始列)
        public Boolean m_bIsSelectBegin = false;    //多选时用

        public string[] m_cbbData;  // 保存配送企业信息,过滤信息用
        public DataTable m_dt;  // 保存查询出来的数据
        private string m_strSql;    // 查询语句
        #endregion
        public frmDelivery()
        {
            InitializeComponent();
        }
        #region 02.自定义方法

        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strInfo = "";
            string strKind = "";
            strKind = this.Name;
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,DeliveryCode-配送单号,DeliveryDetailCode-配送细单号,SupplierCode-配企编号,SupplierName-配企名称,SupplierCode_His-配企编号HIS,SupplierName_His-配企名称HIS,DeliveryTime-配送时间,Code-药品编码,Code_His-药品编码HIS"
                + ",Name-药品名称,Name_His-药品名称HIS,Spec-规格,Spec_His-规格HIS,Manufacturer-生产厂家,Manufacturer_His-生产厂家HIS,RegistrationCode-批准文号,RegistrationCode_His-批准文号HIS,Form-剂型,Form_His-剂型HIS"
                + ",BatchCode-生产批号,MakeDate-生产日期,ExpiredDate-生效日期,Unit-单位,Unit_His-单位HIS,WarehouseRatio-转换率,Price-单价,Price_His-单价HIS,Price_Warehouse-入库价,Amount-数量,WarehouseAmount-入库数,PurchaseAmount-采购数量,Money-金额,InvoiceNo-发票号,InvoiceDate-发票日期,Salesman-业务员"
                + ",StockInStatus-入库状态,StockInTime-入库时间,WarehouseName-药库名称,PurchaseOrderCode-采购单号,PurchaseOrderDetailCode-采购细单号,PurchaseTime-采购时间";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,DeliveryCode,DeliveryDetailCode,SupplierCode,SupplierName,SupplierCode_His,SupplierName_His,DeliveryTime,Code,Code_His"
            + ",Name,Name_His,Spec,Spec_His,Manufacturer,Manufacturer_His,RegistrationCode,RegistrationCode_His,Form,Form_His"
            + ",BatchCode,MakeDate,ExpiredDate,Unit,Unit_His,WarehouseRatio,Price,Price_His,Price_Warehouse,Amount,WarehouseAmount,PurchaseAmount,Money,InvoiceNo,InvoiceDate,Salesman"
            + ",StockInStatus,StockInTime,WarehouseName,PurchaseOrderCode,PurchaseOrderDetailCode,PurchaseTime";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            // 与SqlField同
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "0,80,80,0,140,0,140,80,80,80"
            +",160,160,120,120,160,160,120,120"
            +",80,80,80,60,60,60,80,80,80,80,80,80,80,80,80,80,80,80,80,80";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);
        }

        /// <summary>
        /// 初始化配企信息
        /// </summary>
        private void _initCustomer()
        {
            // 01 取配企信息
            string strSql = "";
            strSql = "select Supplier from(select '未对码|' as Supplier,1000 as ShowOrder  union (select Name + '|' + Code as Supplier,isnull(ShowOrder,0) as ShowOrder from T_Base_SupplierCodeCheck where CheckCodeStatus = 1 and InstitutionCode = '{0}'))A order by ShowOrder desc";
            strSql = string.Format(strSql, AppInfo.m_UserInfo.m_strDeptCode);
            DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                FunctionComm._setInfoToCbb_Dt(cbbCustomer, dt);                
                // 02 保存临时数据(过滤用)
                m_cbbData = new string[dt.Rows.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    m_cbbData[i] = dt.Rows[i][0].ToString();
                }
            }
        }

        /// <summary>
        /// 取查询条件
        /// </summary>
        private Boolean _getQueryWhere(ref string strWhere)
        {
            Boolean bResult = false;
            string strTemp = "";
            strWhere = " InstitutionCode = '{0}'";
            strWhere = string.Format(strWhere, AppInfo.m_UserInfo.m_strDeptCode);
            // 01 取客户名称
            if (cbCustomer.Checked && cbbCustomer.SelectedIndex > -1)
            {
                strTemp = cbbCustomer.Text.Split('|')[1].Trim();
                //if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(SupplierCode_His = '{0}')", strTemp);
                }
            }
            // 02 取配送日期
            if (cbDate.Checked)
            {
                if (dtpDateBegin.Value.ToString("yyyy-MM-dd").CompareTo(dtpDateEnd.Value.ToString("yyyy-MM-dd")) > 0)
                {
                    CommFun._messageBoxShow(string.Format("起始日期大于终止日期！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return bResult;
                }
                else
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(DeliveryTime >= '{0}' and DeliveryTime <= '{1}')", dtpDateBegin.Value.ToString("yyyy-MM-dd"), dtpDateEnd.Value.ToString("yyyy-MM-dd"));
                }
            }
            // 03 取发票日期
            if (cbInvoiceDate.Checked)
            {
                if (dtpInvoiceDateBegin.Value.ToString("yyyy-MM-dd").CompareTo(dtpInvoiceDateEnd.Value.ToString("yyyy-MM-dd")) > 0)
                {
                    CommFun._messageBoxShow(string.Format("起始日期大于终止日期！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                else
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceDate >= '{0}' and InvoiceDate <= '{1}')", dtpInvoiceDateBegin.Value.ToString("yyyy-MM-dd"), dtpInvoiceDateEnd.Value.ToString("yyyy-MM-dd"));
                }
            }
            // 04 商品编号
            if (cbGoodsCode.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Code like '%{0}%')", txtGoodsCode.Text.Trim());
            }
            // 05 商品名称
            if (cbGoodsName.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(Name like '%{0}%')", txtGoodsName.Text.Trim());
            }
            // 06 发票号
            if (cbInvoiceNo.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceNo like '%{0}%')", txtInvoiceNo.Text.Trim());
            }
            //// 07 物流单号
            //if (cbStockOutCode.Checked)
            //{
            //    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(DZJGMLBM like '%{0}%')", txtStockOutCode.Text.Trim());
            //}
            // 08 入库状态
            if (cbStatus.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(StockInStatus,0) = {0})", rbStatus0.Checked ? 0 : 1);
            }
            // 09 入库库房
            if (cbWarehouse.Checked)
            {
                strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(IsNull(WarehouseName,'') = '' or WarehouseName = '{0}')", cbbWarehouse.Text.Split('|')[0].Trim());
            }
            bResult = true;
            return bResult;
        }

        /// <summary>
        /// 信息查询
        /// </summary>
        private void _query()
        {
            if (m_dt != null)
            {
                m_dt.Dispose();
            }
            // 00 取条件:有参数时按参数来取数据
            string strWhere = "";
            if (_getQueryWhere(ref strWhere))
            {
                if (!strWhere.Equals(""))
                {
                    strWhere = string.Format(" where {0}", strWhere);
                }
                // 02 取数据
                string strFieldTemp = AppConfig.m_dictFieldSql[this.Name];
                string strSql = string.Format("SELECT {0} FROM V_DeliveryDetail {{0}} order by DeliveryTime desc", strFieldTemp);
                strSql = string.Format(strSql, strWhere);
                m_dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                m_strSql = strSql;  // 更新数据用
            }
            // 03 显示数据
            DataTable dt = null;
            if (m_dt != null)
            {
                dt = m_dt.Copy();
            }
            _showData(dt);
        }

        /// <summary>
        /// 信息过滤
        /// </summary>
        private void _query0()
        {
            // 00 数据初始化
            DataTable dt = m_dt.Copy();
            DataView dv = dt.DefaultView;
            dv.RowFilter = "1<>1";  // 默认无数据
            // 01 取条件:有参数时按参数来取数据
            string strWhere = "";
            if (_getQueryWhere(ref strWhere))
            {
                dv.RowFilter = strWhere;
            }  
            // 02显示数据
            _showData(dv.ToTable());
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showData(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                // 0101 调整字段顺序
                CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name]);
                // 0102 显示数据
                CommFun._showDataGridView0(dataGridViewX1, dt, AppConfig.m_dictFieldWidth[this.Name], AppConfig.m_dictFieldName[this.Name], false,true); 
            }
            else {
                // 清除数据
                DataTable dtTemp = (DataTable)dataGridViewX1.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }      
            }
            _GetTotalInfo();// lblRecord.Text = string.Format("提示:共有数据信息 {0} 项", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void _init()
        {
            // 01 dataGridViewX1设为不可编辑
            dataGridViewX1.ReadOnly = true;
            dataGridViewX1.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            // 02 初始化日期
            dtpDateBegin.Format = DateTimePickerFormat.Custom;
            dtpDateBegin.CustomFormat = "yyyy-MM-dd";
            dtpDateEnd.Format = dtpDateBegin.Format;
            dtpDateEnd.CustomFormat = dtpDateBegin.CustomFormat;
            dtpInvoiceDateBegin.Format = dtpDateBegin.Format;
            dtpInvoiceDateBegin.CustomFormat = dtpDateBegin.CustomFormat;
            dtpInvoiceDateEnd.Format = dtpDateBegin.Format;
            dtpInvoiceDateEnd.CustomFormat = dtpDateBegin.CustomFormat;

            dtpDateEnd.Value = DateTime.Now;
            dtpDateBegin.Value = dtpDateEnd.Value.AddDays(AppConfig.m_nDateBeforeDistribution * -1);
            dtpInvoiceDateEnd.Value = DateTime.Now;
            dtpInvoiceDateBegin.Value = dtpInvoiceDateEnd.Value.AddDays(AppConfig.m_nDateBeforeInvoice * -1);
            // 03 初始化配企
            _initCustomer();
            // 04 取库房信息
            FunctionComm._setInfoToCbb_Dt(cbbWarehouse, AppInfo.m_dtWarehouse);
            // 05 DataGridView
            _initDgvTitle();
        }

        /// <summary>
        /// 取汇总信息
        /// </summary>
        private void _GetTotalInfo()
        {
            double dTotal = 0;
            for (int i = dataGridViewX1.Rows.Count - 1; i >= 0; i--)
            {
                dTotal += FunctionComm._strToFloat(dataGridViewX1.Rows[i].Cells["Money"].Value.ToString());
            }
            lblRecord.Text = string.Format("提示:共有数据信息 {0} 项,合计:{1}元", dataGridViewX1 == null ? 0 : dataGridViewX1.Rows.Count, dTotal);
        } 
        #endregion

        #region 03.系统事件方法

        private void frm_Load(object sender, EventArgs e)
        {
            _init();
        }

        private void cbbCustomer_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 重绘使可以调整行距
            CommFun._cbbDrawItem(sender, e);
        }

        private void cbbCustomer_TextUpdate(object sender, EventArgs e)
        {
            // 数据过滤
            CommFun._cbbFilter((ComboBox)sender, m_cbbData);
            Cursor = Cursors.Default;
        }

        private void cbCustomer_CheckedChanged(object sender, EventArgs e)
        {
            // 过滤条件变化进行数据过滤
            if (m_dt == null || m_dt.Rows.Count < 1)
            {
                return;
            }
            // 按数据类来处理
            Boolean bRefresh = true;
            Control control = (Control)sender;
            switch (control.Name)
            {
                case "cbbCustomer":
                    bRefresh = cbCustomer.Checked;
                    break;
                case "txtGoodsCode":
                    bRefresh = cbGoodsCode.Checked;
                    break;
                case "txtGoodsName":
                    bRefresh = cbGoodsName.Checked;
                    break;
                case "txtStockOutCode":
                    bRefresh = cbStockOutCode.Checked;
                    break;
                case "txtInvoiceNo":
                    bRefresh = cbInvoiceNo.Checked;
                    break;
                case "rbStatus0":
                case "rbStatus1":
                    bRefresh = cbStatus.Checked;
                    break;
                case "dtpDateBegin":
                case "dtpDateEnd":
                    bRefresh = cbDate.Checked;
                    break;
                case "dtpInvoiceDateBegin":
                case "dtpInvoiceDateEnd":
                    bRefresh = cbInvoiceDate.Checked;
                    break;
            }
            if (bRefresh)
            {
                //_query0();
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            // 数据查询
            _query();           
        }
     
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            // 数据过出
            if (dataGridViewX1 != null && dataGridViewX1.Rows.Count > 0)
            {
                CommFun._ExportExcel("", dataGridViewX1);
            }
        }
        #endregion

        #region GridViewX事件

        private void dataGridViewX1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           // 排序
           CommFun._dgvColumnHeaderSort(sender, e);                    
        }

        private void dataGridViewX1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 单元格双击操作，对于可编辑的列进行编辑状态，否则不能进行编辑,显示详细信息
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            // 显示明细
            DataGridView dgv = (DataGridView)sender;
            DataGridViewColumn newColumn = dgv.Columns[e.ColumnIndex];
            frmInfoDetail frm = new frmInfoDetail();
            frm.m_nRow = e.RowIndex;
            frm.m_dgv = ((DataGridView)sender);
            frm.ShowDialog();
        }
 
        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender,e);
        }

        private void dataGridViewX1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 右键双击设置标题信息 
            if (e.Button == MouseButtons.Right)
            {
                frmDataShowSetup frm = new frmDataShowSetup();
                frm.m_strInfoKind = this.Name;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (frm.m_bIsSaveWidth)
                    {
                        // 保存宽度
                        AppConfig._saveDgvWidth(dataGridViewX1, frm.m_strInfoKind, true);
                        CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        // 刷新数据
                        if (dataGridViewX1.Rows.Count > 0)
                        {
                            btnQuery_Click(null, null);
                        }
                    }
                }
            }
        }
        #endregion        
    }
}